// packageI/scanpictureGoods/scanpictureGoods.js
const app = getApp();
let attr = [{
  name: "推荐商品",
  show: true
},

{
  name: "新品上市",
  show: true
},

{
  name: "热卖商品",
  show: true
},

{
  name: "促销商品",
  show: true
},

{
  name: "限时抢购",
  show: true
}
];
const methods = {
  goback() {
    wx.navigateBack();
  },
  getJson(page) {
    let { image_url, order_field, order_by, brandId,typestring, filterId, attrstr } = this.data;
    let json = { image_url, page: page + 1, order_field, order_by };
    if (brandId) json["search[brand_id]"] = brandId;
    if(attrstr && attrstr.length > 0) json["search[product_attr]"] = attrstr.toString();
    if(filterId && filterId.length > 0) json["search[filtering]"] = filterId.toString();
    if(typestring) json["search[category]"] =  typestring;
    return json
  },
  initData() {
    this.setData({
      page: 0,
      goods: [],
      noMore: false
    })
  },
  getdata() {
    this.initData();
    this.getGoods();
  },
  getMoreData() {
    if (this.data.noMore) return app.tips("没有更多了");
    this.getGoods();
  },
  getGoods() {
    wx.showLoading({
      title: '加载中',
    });
    if (this.data.loading) return false;
    this.setData({ loading: true });
    let json = this.getJson(this.data.page);
    let urlStr = app.getNetAddresss('plugin.scan-picture.frontend.modules.goods.controllers.search.index');
    app._postNetWork({
      url: urlStr,
      data: json,
      success: ({ data: { result, msg, data: { goods_list: data } } }) => {
        wx.hideLoading();
        this.setData({ loading: false });
        if (result) {
          let { goods, page } = this.data;
          goods = goods.concat(data.data);
          this.setData({
            noMore: page == data.last_page,
            goods,
            page: json.page
          })
        } else app.tips(msg);
      },
      fail: (res) => {
        wx.hideLoading();
        this.setData({ loading: true });
      }
    });
  },
  toggle({ currentTarget: { dataset: { val } } }) {
    let order_by = this.data.order_by == 'asc' ? "desc" : "asc";
    this.setData({
      order_by,
      order_field: val
    })
    this.getdata();
  },
  showbox() {
    this.setData({ show: !this.data.show })
  },
}
let mixins = {
  data: {
    screentitle: ["品牌", "分类", "属性", "高级选项"], //筛选标题
    select: "",
    brand: {},
    activeName: '1',
    classification1: [],
    classificationkey: "0",
    classificationId: null,
    classificationId1: null,
    classificationId2: null,
    classificationParentIndex: 0,
    typestring: "",
    attr,
    attrstr: [],
    attrkey: [],
    tagname: [],
    filterId: [],
    showtagnamekey: null
  },
  methods: {
    changetype({ currentTarget: { dataset: { key } } }) {
      this.setData({
        select: key
      });
      this.resetselect();
      switch (key) {
        case 0:
          this.setData({
            show1: true
          });
          break;
        case 1:
          this.setData({
            show2: true
          });
          break;
        case 2:
          this.setData({
            show3: true
          });
          break;
        case 3:
          this.setData({
            show4: true
          });
          break;
        default:
          break;
      }
    },
    //品牌相关的功能
    getbrand() {
      let urlStr = app.getNetAddresss("goods.brand.get-brand");
      app._postNetWork({
        url: urlStr,
        showToastIn: false,
        data: {},
        success: ({ data: { result, data } }) => {
          if (result == 1) this.setData({ brand: data.data });
        }
      });
    },
    screenbrand({ currentTarget: { dataset: { id } } }) {
      this.setData({ brandId: id });
      this.getdata();
      this.showbox();
    },
    onChange({ detail }) {
      this.setData({ activeName: detail });
    },
    //分类相关的功能
    getclassification() {
      let urlStr = app.getNetAddresss("goods.category.search-goods-category");
      app._getNetWork({
        showToastIn: false,
        url: urlStr,
        success: ({ data: { result, data } }) => {
          if (result == 1) {
            this.setData({ classification1: data });
          }
        }
      });
    },
    classificationtype({ currentTarget: { dataset: { id, key } } }) {
      this.setData({
        classification2: [],
        typestring: id,
        classificationkey: key
      });
      if (this.data.classificationId == id) {
        this.setData({
          classificationId: null
        });
        return;
      } else {
        this.setData({
          classificationId: id
        });
      }
      this.setData({
        classificationId1: null,
        classificationId2: null,
        classificationshow: false
      });
    },
    classificationtype1(e) {
      let id = e.currentTarget.dataset.id;
      let parentIndex = e.currentTarget.dataset.parentIndex;

      this.setData({
        typestring: id,
        classificationParentIndex: parentIndex,
        classificationshow: true
      });
      if (this.data.classificationId1 == id) {
        this.setData({
          classificationId1: null
        });
      } else {
        this.setData({
          classificationId1: id
        });
      }

      this.setData({
        classificationId2: null
      });
    },
    classificationtype2(e) {
      let id = e.currentTarget.dataset.id;
      if (this.data.typestring == id) {
        this.setData({
          typestring: null
        });
      } else {
        this.setData({
          typestring: id
        });
      }

      if (this.data.classificationId2 == id) {
        this.setData({
          classificationId2: null
        });
      } else {
        this.setData({
          classificationId2: id
        });
      }
    },
    selectattr(e) {
      let key = e.currentTarget.dataset.key;
      console.log(key);
      //属性选择项
      switch (key) {
        case 0:
          this.findstr("is_recommand", key);
          break;
        case 1:
          this.findstr("is_new", key);
          break;
        case 2:
          this.findstr("is_hot", key);
          break;
        case 3:
          this.findstr("is_discount", key);
          break;
        case 4:
          this.findstr("limit_buy", key);
          break;
      }
      if (this.data.attr[key].show) {
        this.setData({
          ['attr[' + key + '].show']: false
        });
      } else {
        this.setData({
          ['attr[' + key + '].show']: true
        });
      }
    },
    //属性相关的功能
    findstr(attrstr, key) {
      let { attrstr: attrstrD, attrkey } = this.data;
      let index = attrstrD.indexOf(attrstr);
      if (index > -1) {
        attrstrD.splice(index, 1);
        attrkey.splice(index, 1);
      } else {
        attrstrD.push(attrstr);
        attrkey.push(key);
      }
      this.setData({
        attrstr: attrstrD,
        attrkey
      });
    },
    getname() {
      let urlStr = app.getNetAddresss("goods.filtering.index");
      app._getNetWork({
        showToastIn: false,
        url: urlStr,
        success: ({ data: { result, data } }) => {
          if (result == 1) {
            for (let i = 0; i < data.length; i++) {
              for (let y = 0; y < data[i].value.length; y++) {
                if (this.data.filterId.includes(data[i].value[y].id)) {
                  data[i].value[y].record = 2;
                } else {
                  data[i].value[y].record = 1;
                }

              }
            }
            this.setData({
              tagname: data
            });
          }
        }
      });
    },
    //标签组相关功能
    showtagname({ currentTarget: { dataset: { key } } }) {
      if (key == this.data.showtagnamekey) {
        this.setData({
          showtagnamekey: null
        });
        return;
      } else {
        this.setData({
          showtagnamekey: key
        });
      }
    },
    selectname({currentTarget:{dataset:{id,key:key1,keyx:key2}}}) {
      if (this.data.tagname[key1].value[key2].record == 1) {
        if (this.data.filterId.includes(id)) {
          return;
        } else {
          let filterId = this.data.filterId;
          filterId.push(id);
          this.setData({
            filterId: filterId
          });
        }
        this.setData({
          ['tagname.[' + key1 + '].value[' + key2 + '].record']: 2
        });
      } else {
        let index = this.data.filterId.indexOf(id);
        let filterId = this.data.filterId;
        filterId.splice(index, 1);
        this.setData({
          filterId: filterId
        });
        this.setData({
          ['tagname.[' + key1 + '].value[' + key2 + '].record']: 1
        });
      }
    },
    screen(){
      this.getdata();
      this.showbox();
    },
    resetnames() {
      this.setData({
        namestring: null,
        showtagnamekey: null,
        namekey: null,
        brandId: "",
        attrstr: [],
        filterId: [],
        attrkey:[],
        typestring: "",
        classificationkey: null,
        classificationkey1: null,
        classificationkey2: null,
        attr
      });
      for (let i = 0; i < this.data.tagname.length; i++) {
        for (let y = 0; y < this.data.tagname[i].value.length; y++) {
          if (this.data.tagname[i].value[y].record == 2) {
            this.setData({
              ['tagname.[' + i + '].value[' + y + '].record']: 1
            });
          }
        }
      }
    },
  }
}
Page({

  /**
   * 页面的初始数据
   */
  data: {
    image_url: "",
    goods: [],
    page: 0,
    isLoading: false,
    loading: false,
    noMore: false,
    goods_template: {
      names: "04",
      type: "goodsList"
    },
    order_by: "",
    order_field: "",
    sortList: [
      { name: "评价", val: "comment_num" },
      { name: "销量", val: "show_sales" },
      { name: "价格", val: "price" },
    ],
    show: false,
    ...mixins.data
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function ({ url }) {
    this.setData({ image_url: url });if (url) {
      this.getdata();
      this.getbrand();
      this.getclassification();
      this.getname();
    } else this.goback();
  },
  ...methods,
  ...mixins.methods,
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    this.getMoreData();
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})